<template>
  <div >
      <vab-card shadow="always">
          <template #default>
              <div class="flex_sb">
                  <div class="flex leve_title">
                      信用档案创建
                  </div>
                  <div class="flex_just_end">
                      <el-button size="small" v-if="_IsSave" class="button_update" @click="_customerPriceCreate(2)">暂存</el-button>
                      <el-button size="small" @click="handleClick('back')">取消</el-button>
                      <el-button size="small" type="primary" @click="_customerPriceCreate(1)">提交</el-button>
                  </div>
              </div>
          </template>
      </vab-card>

      <div v-loading="createLoading">
         <!-- 产品价格明细-create -->
        <CreditTableCreate 
            :isWarn="isWarn" 
            :fromPage="fromPage"
            :ref="(el) => creditTableCreateRef = el" 
        />
      </div>
  </div>
</template>

<script setup lang="ts">

defineOptions({
  name: 'CreditCustomCreate'
})

/**
* @import
*/
import CreditTableCreate from './component/CreditTableCreate.vue'
import { organization_list } from '~/src/api/dms/organization';

import { crediCreate, crediInfo, crediSearch, crediUpdate } from '~/src/api/dms/credit';
import { options_list } from '~/src/api/dms/options';


/**
* @var
*/
const proxy: any = getCurrentInstance()?.proxy
const router = useRouter()
const route = useRoute()
const { from, handleStatus } = route.query
let fromPage = ref<any>(from == 'toHandle' ? 'copy' : from)
let fromID = ref(route.query.id)

const creditTableCreateRef = ref()

// 是否有错误提示
const isWarn = ref(false)

let screenObj = ref<any>(null)
let createLoading = ref<any>(false)
/**
* @method
*/

//  点击事件
const handleClick = async (value: any) => {
  if (value == 'back') {
    router.go(-1)
    return
  }
}
// 筛选项
const _GetProductSearch = async () => {
  try {
    const res = await crediSearch()
    const orgRes = await organization_list({})
    const currencyRes = await options_list({ module: 'currency' })
    screenObj = await res.data
    screenObj.org_list = await orgRes.data
    screenObj.currency = currencyRes.data
    // 组件获取筛选项
    creditTableCreateRef.value.getScreen(screenObj)
  } catch (error) { }
}

// 创建
const _customerPriceCreate = async (type: number) => {

  // 基本信息 校验
  const baseValidate = await creditTableCreateRef.value.baseFormRef.validate((valid: any) => {
    if (valid) return true
    return false
  })

  if (!baseValidate) return
  const baseForm = creditTableCreateRef.value.baseForm

  let productList: any = []
  productList = creditTableCreateRef.value.productList.map((item: any) => {
    let data: any = {
      customer_id: `${item.customer_id}`,//客户uid
      customer_number: item.customer_number,//客户编码
      currency_id: item.currency_id,//币别
      currency_name: item.currency_name,//币别名称
      credit_amount: item.credit_amount,//信用额度
      credit_status: item.credit_status,//信用状态
      check_role_id: item.check_role_id,//检查规则
      check_role_name: item.check_role_name//检查规则名称
    }

    if (from == 'toHandle') data.id = item.id || 0

    return data
  })

  // 判空
  let VoidJudgment = false
  // 校验价格
  if (productList.length) {
    // 判空
    VoidJudgment = productList.some((item: any) => {
      return !item.customer_id ||
        !item.customer_number ||
        !item.currency_id ||
        (!item.credit_amount && item.credit_amount != 0) ||
        !item.credit_status ||
        !item.check_role_id
    })
  }

  isWarn.value = false
  if (VoidJudgment) {
    proxy.$Message('请正确填写信用对象设置信息!', 'warning')
    isWarn.value = true
    return
  }

  let data: any = {
    ctrl_scope: baseForm.ctrl_scope || '',//控制范围
    object_type: baseForm.object_type || '',//信用对象范围
    org_id: baseForm.org_id || '',//授信组织
    note: baseForm.note || '',
    type,//类型，1提交2暂存 --必填
    customer_list: productList || []//产品列表
  }

  if (from == 'copy') baseForm.id = ''

  const { id } = baseForm

  // 通过有无id判断 
  if (id) {
    data.id = id
    crediUpdate({ ...data }).then((res: any) => {
      proxy.$Message('提交成功', 'success')
      router.go(-1)
    }).catch(err => {
    })
  } else {
    crediCreate({ ...data }).then((res: any) => {
      proxy.$Message(`${type == 1 ? '提交' : '暂存'}成功`, 'success')
      router.go(-1)
    }).catch(err => {

    })
  }
}

// 获取更新数据
const _GetUpdateInfo = async () => {
  createLoading.value = true
  try {
    const res = await crediInfo({ id: fromID.value })
    creditTableCreateRef.value.getUpdateData(res.data)
    setTimeout(() => {
      createLoading.value = false
    }, 1000);

  } catch (error) { }
}

/**
* @实例
*/
// 是否显示暂存
const _IsSave = computed(() => {
  if (from == 'update') return false
  if (handleStatus == '3') return false
  return true
})

onMounted(async () => {
  await _GetProductSearch()
  if (fromPage.value != 'create') _GetUpdateInfo()
})

</script>

<style scoped></style>